<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="请输入您的用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
          <div class="line"></div>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        placeholder="请输入您的密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
          <div class="line"></div>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <!--    <el-button class="reset-btn" :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>-->
    <el-button size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登&nbsp;录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
// import { UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
// import md5 from "md5";
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: ""
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const res: any = await loginApi({ ...loginForm });
      if (res.code === 440) {
        const msg = escape(res.message);
        router.push({ path: "/modify_password", query: { msg: msg, username: loginForm.username } });
        return;
      }
      userStore.setToken(res.data.token);
      userStore.setUserInfo(res.data);
      localStorage.setItem("token", res.data.token);
      if (route.query.refer) {
        const refer = route.query.refer;
        let path = "";
        /*
          refer携带其他参数的情况下进入本系统（通过?判断）
          - 携带其他参数=> &拼接
          - 未携带其他阐述=> ?拼接
          example  http://localhost:8088/auth#/login?refer=http://localhost:8089/message_overview#/overview?id=1234&&keyfrom=baidu
        */
        const spliSymbol = refer.indexOf("?") !== -1 ? "&" : "?";
        path = refer + `${spliSymbol}token=` + localStorage.getItem("token");
        window.location.replace(path);
        return;
      }

      sessionStorage.setItem("menu", "webPortal");

      // 2.添加动态路由
      await initDynamicRouter("webPortal");

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);
      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录" + loginForm.username,
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
